<?php

declare (strict_types = 1);

namespace app\model;

/**
 * 标签表
 * @mixin \think\Model
 */
class Tag extends Base
{
    protected $pk = "tagid";

    protected $schema = [
        "tagid" => "int",  // 
        "tagname" => "varchar",  // 标签
        "nums" => "int"  // 文章数
    ];

    protected $autoWriteTimestamp = false;    

    public static function queryList($tagname)
    {
        return self::where('tagname','LIKE', '%'.$tagname.'%')->field('tagid, tagname')->select();
    }

    public static function saveTags(array $tags, int $infoid = 0, int $cid = 0)
    {
        foreach ($tags as  $tagname) {
            $tag = self::where('tagname', $tagname)->find();

            if ($tag == null) {
                $tag = new static;
                $tag->tagname = $tagname;
            }
            $tag->nums += 1;
            $tag->save();

            TagArticle::create([
                'infoid' => $infoid,
                'cid'    => $cid,
                'tagid'  => $tag->tagid
            ]);
        }
    }

    public static function decNums(array $tags, int $infoid=0)
    {
        foreach ($tags as  $tagname) {
            $tag = self::where('tagname', $tagname)->find();

            if ($tag != null) {
                $tag->nums = $tag->nums - 1;
                
                $tag->save();

                TagArticle::where(['infoid'=>$infoid, 'tagid'=>$tag->tagid])->delete();
            }
        }
    }
}
